/*******************************************************************************
 * Copyright (c) 2008-2009 zhang yuexiang.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 
package org.xfeep.asura.bootstrap;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.xfeep.asura.core.ComponentDefinition;
import org.xfeep.asura.core.ComponentManager;

/**
 * XmlDirComponentLoader  can load all component definitations from  all xml files in one given folder.
 * Every one of these xml files is compatible with  asura-composite-1.0.xsd 
 * @author zhang yuexiang
 *
 */
public class XmlDirComponentLoader implements ComponentLoader {

	protected File dir;
	protected JAXBContext jaxbContext;

	public XmlDirComponentLoader() {
		this("composites");
	}
	
	public XmlDirComponentLoader(File dir) {
		this.dir = dir;
	}
	
	public XmlDirComponentLoader(String dir) {
		this(new File(dir));
	}
	
	
	public List<ComponentDefinition> getStaticLoadComponents(
			ClassLoader classLoader) throws IOException {
		File[] fs = dir.listFiles();
		if (fs != null){
			try {
				if (jaxbContext == null){
					jaxbContext = JAXBContext.newInstance(CompositeDefinitionInfo.class);
				}
				List<ComponentDefinition> list = new ArrayList<ComponentDefinition>();
				for (File f : fs){
					if (f.isDirectory()){
						XmlDirComponentLoader subLoader = new XmlDirComponentLoader(f);
						subLoader.jaxbContext = jaxbContext;
						list.addAll(subLoader.getStaticLoadComponents(classLoader));
					}
					if (f.getName().toLowerCase().endsWith(".xml")){
						XmlComponentLoader xl = new XmlComponentLoader(f);
						xl.setJaxbContext(jaxbContext);
						list.addAll( xl.getStaticLoadComponents(classLoader) );
					}
				}
				return list;
			} catch (JAXBException e) {
				throw new IOException("load component failed in dir " + dir.getAbsolutePath(), e);
			}
		}else{
			return Collections.EMPTY_LIST;
		}
	}

	public void initialize(ComponentManager componentManager) {
	}

	public void setupComponentDynamicLoadListener(
			ComponentDynamicLoadListener listener) {
	}

}
